<?php
/**
 * 微信公众号接口
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-10-11
 * Time: 10:06
 */

namespace App\Services\Wx;



use App\Libs\httpUtil;
use App\Libs\OSS;
use Illuminate\Support\Facades\Redis;

class WxService
{
    /**
     * 获取accessToken
     * @return bool
     */
    public function getAccessToken()
    {
        $data = \RedisDB::get(env("APP_NAME").'-access_token');
        if($data){
            $accessToken = json_decode($data, true);
            return $accessToken['access_token'];
        }else{
         return   $this->refreshAccessToken();
        }
    }

    /**
     * 刷新accessToken
     * @return bool
     */
    private function refreshAccessToken()
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".env("WX_APPID")."&secret=".env("WX_APPKEY");
        $http = new httpUtil();
        $data = $http->http_get($url);
        if(!$data){
            return false;
        }

        $result = json_decode($data, true);
        if(!empty($result['errcode'])){
            \Log::error('WxService  refreshAccessToken'.$data);
            return false;
        }
        $result['createTime'] = date("Y-m-d H:i:s",time());

        \RedisDB::setex(env("APP_NAME").'-access_token',$result['expires_in'],json_encode($result));
        return $result['access_token'];
    }



    public function getJsapiTicket()
    {
        $data = \RedisDB::get(env("APP_NAME").'-jsapi_ticket');
        if($data){
            $accessToken = json_decode($data, true);
            return $accessToken['ticket'];
        }else{
            return   $this->refreshJsapiTicket();
        }
    }

    /**
     *  微信JS接口的临时票据
     * @return bool
     */
    private function refreshJsapiTicket()
    {
        $accessToken = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$accessToken."&type=jsapi";
        $http = new httpUtil();
        $data = $http->http_get($url);
        if(!$data){
            return false;
        }

        $result = json_decode($data, true);
        if(!empty($result['errcode'])){
            \Log::error('WxService  refreshJsapiTicket'.$data);
            return false;
        }

        $result['createTime'] = date("Y-m-d H:i:s",time());

        \RedisDB::setex(env("APP_NAME").'-jsapi_ticket',$result['expires_in'],json_encode($result));
        return $result['ticket'];
    }

    /**
     * 通过mediaId获取文件地址
     * @param $mediaId
     * @return bool|string
     */
    public function getFilePath($mediaId)
    {
        $flag = substr($mediaId,0,4);
       if($flag == "http") {
            return $mediaId;
       }
        $accessToken = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=".$accessToken."&media_id=".$mediaId;
        $newName = time(). ".jpg" ;
        $path = 'groupon/'.$newName ;
        $model = new OSS();
        $realPath = 'static/'.$newName;
        file_put_contents($realPath, file_get_contents($url));
        $result =  $model->publicUpload('xcxhn',$path,$realPath,[ 'ContentType' => "image/jpeg"]);
        if($result){
            @unlink($realPath);
            $data = $model->url.$newName;
            return $data;
        }else{
            return false;
        }
    }

    /**
     * 订单购买成功通知
     * @return string
     */
    public function sendOrderSuccessTemplate($openId,$name,$time,$site,$tempUrl)
    {
        $accessToken = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$accessToken;
        $paramArr = [
        "touser"=>$openId,
           "template_id"=>"McHFIVrJ_jxZ9Jjxicenxj8BighYdvndT1hqFHRQdVs",
           "url"=>$tempUrl,
           "data"=>[
            "first"=>[
                "value"=>"恭喜您，课程报名成功",
                "color"=>"#173177"
            ],
               "keyword1"=>[
                    "value"=>$name,
                    "color"=>"#173177"
            ],
               "keyword2"=>[
                   "value"=>date("Y-m-d",strtotime($time)),
                   "color"=>"#173177"
               ],
                "keyword3"=>[
                    "value"=>$site,
                    "color"=>"#173177"
                ],
                "keyword4"=>[
                    "value"=>"报名成功",
                    "color"=>"#173177"
                ],
               "remark"=>[
                   "value"=>"请准时上课！",
                   "color"=>"#173177"
               ],
           ]
       ];
        $paramObj = json_encode($paramArr);
        $http = new httpUtil();
        $status = $http->http_post($url,$paramObj);
        return $status;
    }

}